import axios from 'axios'
import Image from 'next/image'
import MarkdownRenderer from './MarkdownRenderer'
import { useState, useRef, useEffect } from 'react'
import { Drawer } from 'antd'
import { AiOutlineSend, AiOutlineHistory, AiOutlineDown, AiOutlinePlusCircle } from "react-icons/ai";
import { Tooltip, List } from 'antd';
function About() {
  const [chat, setChat] = useState([])
  const questionInput = useRef(null)
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [historyChat, setHistoryChat] = useState([])
  const [chatIndex, setChatIndex] = useState('new')
  useEffect(() => {
    const hChat = JSON.parse(localStorage.getItem('historyChat'))
    if (hChat) {
      setHistoryChat(hChat)
    } else {
      localStorage.setItem('historyChat', JSON.stringify([]))
    }
  }, [])
  const enterSendQuestion = (e) => {
    if (e.key === 'Enter' && e.ctrlKey) {
      // 按下 Ctrl + Enter 键，换行
      questionInput.current.value = e.target.value + '\n'
    } else if (e.key == 'Enter') {
      e.preventDefault();
      sendQuestion()
    }
  }

  const sendQuestion = () => {
    setLoading(true)
    const question = questionInput.current.value
    axios({
      url: '/api/chatgpt',
      method: 'POST',
      data: {
        text: question,
        apiKey: '0471f49952a7d4a529e8d1e48c16fcbd'
      }
    }).then((res) => {
      const answer = res.data;
      const newData = { question: question, answer: answer }
      setChat(prevChat => [...prevChat, newData]);
      setLoading(false)
    })

    questionInput.current.value = ''
  }

  const createNewChat = () => {
    axios({
      url: '/api/chatgpt',
      method: 'POST',
      data: {
        text: '删除会话',
        apiKey: '0471f49952a7d4a529e8d1e48c16fcbd'
      }
    }).then((res) => {
      console.log(res)
      if (chatIndex == 'new') {
        const historyData = [chat, ...historyChat]
        setHistoryChat(historyData)
        localStorage.setItem('historyChat', JSON.stringify(historyData))
      } else {
        const historyData = historyChat.map((item, index) => {
          if (index == chatIndex) {
            return chat
          }
          return item
        })
        setHistoryChat(historyData)
        localStorage.setItem('historyChat', JSON.stringify(historyData))
      }


      setChat([])
    }).catch((err) => {
      console.log(err)
    })

  }

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };

  const enterHistoryChat = (index) => {
    setChat(historyChat[index])
    setChatIndex(index)
    setOpen(false);
  }


  return (
    <>
      <div className="bg-white shadow-md p-3 mb-10">

        <h1 className="text-3xl">This is ChatGPT!</h1>
      </div>
      <div className='flex flex-col items-center' >

        <div className='flex flex-col container mx-auto h-chatH bg-white rounded-lg'>
          <h2 className='flex justify-center p-2 text-center shadow'><Image className='block mr-2' src='/images/chatLogo.png' alt='chatLogo' width={30} height={30}></Image>ChatGPT-3.5</h2>
          <div className='flex-1  overflow-y-auto scroll-smooth scrollbar-w-0.5 scrollbar-h-5 scrollbar-track-gray-200 scrollbar-thumb-gray-50 p-2 pb-20'>
            {chat.map((item, i) => (<div key={i}>
              <div className='flex flex-col items-end m-2'>
                <Image className='block' src='/images/avatar.png' alt='chatLogo' width={30} height={30}></Image>
                <p className='m-2 p-4 bg-gray-300 rounded-lg'>
                  <MarkdownRenderer markdownText={item.question} />
                </p>

              </div>
              <div className='flex flex-col items-start m-2'>
                <Image className='block' src='/images/chatLogo.png' alt='chatLogo' width={30} height={30}></Image>
                <p className='m-2 p-4 bg-gray-300 rounded-lg'>
                  <MarkdownRenderer markdownText={item.answer} />
                </p>

              </div>

            </div>))}
            {loading && <div className='flex justify-center'><Image className='block animate-spin' src='/images/loading.png' alt='chatLogo' width={30} height={30}></Image></div>}

          </div>
          {/* 输入框部分 */}
          <div>

            <div className='w-24 flex justify-between cursor-pointer text-lg px-3 pt-3'>
              <AiOutlineDown />
              <Tooltip placement="top" title='聊天历史'>
                <AiOutlineHistory onClick={showDrawer} className='text-lg' />
              </Tooltip>
              <Tooltip placement="top" title='新聊天'>
                <AiOutlinePlusCircle onClick={createNewChat} />
              </Tooltip>
            </div>

            <div className='relative p-3'>
              <textarea className='h-24 w-full p-2 pr-10 pb-10 bg-gray-100 border-spacing-1 rounded-lg focus:shadow-lg focus:border border-gray-300 text-xs focus:outline-none resize-none focus:bg-white' rows="4" placeholder="请输入问题..." ref={questionInput} onKeyDown={enterSendQuestion}></textarea>
              <button className='absolute text-lg bottom-8 right-8' onClick={sendQuestion}><AiOutlineSend /></button>
            </div>

          </div>

        </div>

      </div >
      {/* 底部弹出聊天历史记录 */}
      <Drawer

        placement="bottom"
        onClose={onClose}
        open={open}
        title="聊天历史"
        getContainer={false}
      >
        <List
          itemLayout="horizontal"
          dataSource={historyChat}
          renderItem={(item, index) => (
            <List.Item className=' hover:shadow-lg transition-all duration-300' onClick={() => enterHistoryChat(index)}>
              <List.Item.Meta
                title={<h3 className='px-3'>{item[0].question}</h3>}
                description={<p className='truncate px-3'>{item[0].answer}</p>}
              />
            </List.Item>
          )}
        />
      </Drawer>
    </>

  )
}

export default About